package com.mission.schedule.my160920;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.google.gson.Gson;
import com.lcf.refreshlibrary.ILoadingLayout;
import com.lcf.refreshlibrary.PullToRefreshBase;
import com.lcf.refreshlibrary.PullToRefreshScrollView;
import com.mission.schedule.R;
import com.mission.schedule.activity.BaseActivity;
import com.mission.schedule.activity.EndSoundActivity;
import com.mission.schedule.adapter.MyFriendsFragmentAdapter;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.FriendsBean;
import com.mission.schedule.constants.PostSendMainActivity;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.db.DBHelper;
import com.mission.schedule.my160920.adapter.EndFrendAdapter;
import com.mission.schedule.my160920.adapter.FindFrendAdapter;
import com.mission.schedule.my160920.bean.FriendBackBean;
import com.mission.schedule.my160920.bean.FriendBean;
import com.mission.schedule.my160920.bean.FriendDeleteScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownBackBean;
import com.mission.schedule.my160920.widget.OnRefreshRecyclerViewHeader;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import de.greenrobot.event.EventBus;

/**
 * Created by liwei on 2016/9/26.
 */

public class NewEndTaskActivity extends BaseActivity {

    private RecyclerView mRecyclerView;
    //组合bean
    private List<FrendBean> frendBeanList;
    //好友bean
    private List<FriendBean> friendBeanList;
    //下行日程bean
    private List<FriendDownAllScheduleBean> firendDownBeanList;

    private List<FriendDeleteScheduleBean> friendDeleteScheduleBeanList;

//    private SwipeRefreshLayout swipeRefreshLayout;

    String updatetime;
    String persondowntime;

    SharedPrefUtil sharedPrefUtil = null;
    String userID = "0";

    EndFrendAdapter endFrendAdapter;

    private int listsize = 0;
    PullToRefreshScrollView pull_refresh_scrollview;

    @Override
    protected void setListener() {

    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.new_my_end_task);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        sharedPrefUtil = new SharedPrefUtil(this, ShareFile.USERFILE);
        userID = sharedPrefUtil.getString(this, ShareFile.USERFILE,
                ShareFile.USERID, "0");
        updatetime = sharedPrefUtil.getString(this,
                ShareFile.USERFILE, ShareFile.UPDATESETTIME, "2016-01-01%2B00:00:00");

        persondowntime = sharedPrefUtil.getString(this, ShareFile.USERFILE, ShareFile.PERSONDOWNTIME, "2016-01-01");

//        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.end_swipe);
//        swipeRefreshLayout.setColorSchemeResources(R.color.xinjianricheng_bg);
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//
//            }
//        });
        pull_refresh_scrollview = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
        pull_refresh_scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (NetUtil.getConnectState(NewEndTaskActivity.this) != NetUtil.NetWorkState.NONE) {
                    DownFrend();
                } else {
                    Toast.makeText(NewEndTaskActivity.this, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                    pull_refresh_scrollview.onRefreshComplete();
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
        mRecyclerView = (RecyclerView) findViewById(R.id.end_recylerview);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setHasFixedSize(true);

        frendBeanList = new CopyOnWriteArrayList<>();

        DBtoAllList();

        endFrendAdapter = new EndFrendAdapter(frendBeanList, this, handler);
        final ScrollLinearLayoutManager scrollLinearLayoutManager = new ScrollLinearLayoutManager(this);
        mRecyclerView.setLayoutManager(scrollLinearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(endFrendAdapter);

//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                int topRowVerticalPosition =
//                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
//                toLoadLayout.setRefreshEnabled(topRowVerticalPosition >= 0);
//            }
//
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//            }
//        });


        findViewById(R.id.ly_top_ll_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        /**
         * end
         */
        lyb = new lybo();
        IntentFilter ifd = new IntentFilter();
        ifd.addAction("end");
        registerReceiver(lyb, ifd);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent();
        if (endtype == true) {
            setResult(Activity.RESULT_OK, intent);
        } else {
            setResult(Activity.RESULT_CANCELED, intent);
        }
        finish();
    }

    lybo lyb;

    @Override
    protected void setAdapter() {

    }


    //结束任务回调
    private static int END_RESULT = 901;
    //留言回调
    private static int LY_RESULT = 903;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == END_RESULT) {
            if (resultCode == Activity.RESULT_OK) {
                DownFrend();
            }
        }
        if (requestCode == LY_RESULT) {
            if (resultCode == Activity.RESULT_OK) {
                DownFrend();
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 3:
                    sendMess(004);
                    endFrendAdapter = new EndFrendAdapter(frendBeanList, NewEndTaskActivity.this, handler);
                    mRecyclerView.setLayoutManager(new LinearLayoutManager(NewEndTaskActivity.this.getApplicationContext()));
                    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                    mRecyclerView.setAdapter(endFrendAdapter);
                    break;
                case 4:
                    pull_refresh_scrollview.onRefreshComplete();
                    break;
                case 5:
                    break;
                case 6:
                    break;
                case 100:
                    listsize = msg.arg2;
                    break;
            }
        }
    };

    /**
     * 2016 09 20
     */
    List<Integer> uid = new ArrayList<>();

    /**
     * 将数据库的数据转换为一个Bean
     */
    private void DBtoAllList() {

        /**
         * 检查是否有发出的6.0.0版本的表,没有则创建
         */
        DBHelper helper = new DBHelper(this);
        if (!helper.tabIsExist("FriendsListTable")
                && !helper.tabIsExist("FriendDownAllScheduleBean")
                && !helper.tabIsExist("FriendCommonReply")) {
            App.getDBcApplication().createTbale();
            sharedPrefUtil
                    .putString(
                            this,
                            ShareFile.USERFILE,
                            ShareFile.PERSONDOWNTIME,
                            "2016-01-01");
            sharedPrefUtil
                    .putString(
                            this,
                            ShareFile.USERFILE,
                            ShareFile.UPDATESETTIME,
                            "2016-01-01%2B00:00:00");
        }


        List<FriendBean> friendBeanList = App.getDBcApplication().backFriendsList(userID);
        List<FriendDownAllScheduleBean> friendDownAllScheduBeanList = App.getDBcApplication().getAllFriendSchedule();
        frendBeanList.clear();

        for (int i = 0; i < friendBeanList.size(); i++) {
            /**
             * uid : 52432
             * id : 767
             * cpId : 260975
             * uPersontag : 加油加油！
             * uToCode : web
             * remark : null
             * uPortrait : 20150925136/638645.jpg
             * dateUpdate : 2016-09-14T10:58:03
             * uNickName : 韩雪h
             * type : 0
             * uBackgroundImage : 20160820/933727.png
             */

            /**
             * 相同的日程
             */
            for (int j = 0; j < friendDownAllScheduBeanList.size(); j++) {
                if (friendBeanList.get(i).getCpId().equals(friendDownAllScheduBeanList.get(j).getCpId())
                        && friendDownAllScheduBeanList.get(j).getPoststate().equals("2")) {
                    Log.e("TAG", friendDownAllScheduBeanList.get(j).getPoststate() + "----getPoststate");
                    uid.add(j);
                }

            }

            try {
                if (uid.size() > 0) {

                    FrendBean frendBean = new FrendBean();

                    frendBean.setF_uNickName(friendBeanList.get(i).getuNickName());
                    frendBean.setF_uPersontag(friendBeanList.get(i).getuPersontag());
                    frendBean.setF_uPortrait(friendBeanList.get(i).getuPortrait());
                    frendBean.setF_uToCode(friendBeanList.get(i).getuToCode());
                    frendBean.setF_type(friendBeanList.get(i).getType());
                    frendBean.setF_uBackgroundImage(friendBeanList.get(i).getuBackgroundImage());
                    frendBean.setF_remark(friendBeanList.get(i).getRemark());
                    frendBean.setF_dateUpdate(friendBeanList.get(i).getDateUpdate());
                    frendBean.setF_cpId(friendBeanList.get(i).getCpId());
                    frendBean.setF_id(friendBeanList.get(i).getId());
                    frendBean.setF_uid(friendBeanList.get(i).getUid());

                    frendBean.setViewType(1);
                    frendBean.setUid(friendBeanList.get(i).uid);
                    frendBeanList.add(frendBean);

                    List<FriendDownAllScheduleBean> friendList = new ArrayList<>();
                    for (int u = 0; u < uid.size(); u++) {
                        friendList.add(friendDownAllScheduBeanList.get(uid.get(u)));
                    }

                    Comparator<FriendDownAllScheduleBean> comparator = new Comparator<FriendDownAllScheduleBean>() {
                        @Override
                        public int compare(FriendDownAllScheduleBean lhs, FriendDownAllScheduleBean rhs) {
                            return rhs.id.compareTo(lhs.id);
                        }
                    };

                    Collections.sort(friendList,comparator);
                    int diffnum = 0;
                    int difnum = 0;
                    for (int u = 0; u < friendList.size(); u++) {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = new Date(System.currentTimeMillis());

                        Date d1 = df.parse(df.format(date));
                        Date d2 = df.parse(friendList.get(u).cdate);
                        long diff = d1.getTime() - d2.getTime();
                        if (friendList.get(u).poststate.equals("2") && diff > 0) {
                            difnum++;
                        }
                    }
                    for (int u = 0; u < friendList.size(); u++) {
                        /**
                         * CAlarmsound : g_220* CAlarmsoundDesc : 短提示音* CLightAppId : 0* COpenstate : 0
                         * CPostpone : 1* CRecommendName : 张力川* CTags :* CType : 0* CTypeDesc :* CTypeSpare :* atype : 0* calendaId : 0* cbeforTime : 0
                         * * cdate : 2016-09-19* changTime : 2016-09-19T11:04:53* cisAlarm : 1* cpId : 232380* cretetime : 2016-09-19T11:04:51
                         * ctime : 09:58* downNum : 1* downstate : 0* endNum : 0* endState : 0* id : 396* imgPath :
                         * lyNum : 10* message : 已结束=0/1 一直不准确，不及时。需测试解决。* parReamrk :* pid : 0* poststate : 0* remark :* remark1 :
                         * remark2 :* remark3 :* repCalendaState : 0* repCalendaTime :* repColorType : 0* repDisplayTime : 0
                         * repInStable : 1* repIsPuase : 0* repState : 0* repType : 0* repTypeParameter :* repdatetwo :
                         * repinitialcreatedtime :* replastcreatedtime :* repnextcreatedtime :* repstartdate :* repstatetwo : 0
                         * schIsImportant : 0* status : 1* uid : 52432* webUrl :
                         */

                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = new Date(System.currentTimeMillis());

                        Date d1 = df.parse(df.format(date));
                        Date d2 = df.parse(friendList.get(u).cdate);
                        long diff = d1.getTime() - d2.getTime();


                        if (friendList.get(u).poststate.equals("2") && diff > 0) {

                            FrendBean frendBean2 = new FrendBean();

                            frendBean2.setF_uNickName(friendBeanList.get(i).uNickName);
                            frendBean2.setF_uPortrait(friendBeanList.get(i).uPortrait);

                            frendBean2.setCAlarmsound(friendList.get(u).CAlarmsound);
                            frendBean2.setCAlarmsoundDesc(friendList.get(u).CAlarmsoundDesc);
                            frendBean2.setCLightAppId(friendList.get(u).CLightAppId);
                            frendBean2.setCOpenstate(friendList.get(u).COpenstate);
                            frendBean2.setCPostpone(friendList.get(u).CPostpone);
                            frendBean2.setCRecommendName(friendList.get(u).CRecommendName);
                            frendBean2.setCTags(friendList.get(u).CTags);
                            frendBean2.setCType(friendList.get(u).CType);
                            frendBean2.setCTypeSpare(friendList.get(u).CTypeSpare);
                            frendBean2.setAtype(friendList.get(u).atype);
                            frendBean2.setCalendaId(friendList.get(u).calendaId);
                            frendBean2.setCbeforTime(friendList.get(u).cbeforTime);
                            frendBean2.setCdate(friendList.get(u).cdate);
                            frendBean2.setChangTime(friendList.get(u).changTime);
                            frendBean2.setCisAlarm(friendList.get(u).cisAlarm);
                            frendBean2.setCpId(friendList.get(u).cpId);
                            frendBean2.setCretetime(friendList.get(u).cretetime);
                            frendBean2.setCtime(friendList.get(u).ctime);
                            frendBean2.setDownNum(friendList.get(u).downNum);
                            frendBean2.setEndNum(friendList.get(u).endNum);
                            frendBean2.setDownstate(friendList.get(u).downstate);
                            frendBean2.setId(friendList.get(u).id);
                            frendBean2.setImgPath(friendList.get(u).imgPath);
                            frendBean2.setLyNum(friendList.get(u).lyNum);
                            frendBean2.setMessage(friendList.get(u).message);
                            frendBean2.setParReamrk(friendList.get(u).parReamrk);
                            frendBean2.setPoststate(friendList.get(u).poststate);
                            frendBean2.setPid(friendList.get(u).pid);
                            frendBean2.setRemark(friendList.get(u).remark);
                            frendBean2.setRemark1(friendList.get(u).remark1);
                            frendBean2.setRemark2(friendList.get(u).remark2);
                            frendBean2.setRemark3(friendList.get(u).remark3);
                            frendBean2.setRepCalendaState(friendList.get(u).repCalendaState);
                            frendBean2.setRepCalendaTime(friendList.get(u).repCalendaTime);
                            frendBean2.setRepColorType(friendList.get(u).repColorType);
                            frendBean2.setRepDisplayTime(friendList.get(u).repDisplayTime);
                            frendBean2.setRepInStable(friendList.get(u).repInStable);
                            frendBean2.setRepIsPuase(friendList.get(u).repIsPuase);
                            frendBean2.setRepState(friendList.get(u).repState);
                            frendBean2.setRepType(friendList.get(u).repType);
                            frendBean2.setRepTypeParameter(friendList.get(u).repTypeParameter);
                            frendBean2.setRepdatetwo(friendList.get(u).repdatetwo);
                            frendBean2.setRepinitialcreatedtime(friendList.get(u).repinitialcreatedtime);
                            frendBean2.setReplastcreatedtime(friendList.get(u).replastcreatedtime);
                            frendBean2.setRepnextcreatedtime(friendList.get(u).repnextcreatedtime);
                            frendBean2.setRepstartdate(friendList.get(u).repstartdate);
                            frendBean2.setRepstartdate(friendList.get(u).repstatetwo);
                            frendBean2.setSchIsImportant(friendList.get(u).schIsImportant);
                            frendBean2.setStatus(friendList.get(u).status);
                            frendBean2.setUid(friendList.get(u).uid);
                            frendBean2.setWebUrl(friendList.get(u).webUrl);
                            frendBean2.setRepState(friendList.get(u).repState);
                            frendBean2.setRepState(friendList.get(u).repState);
                            frendBean2.setCount(0);
                            frendBean2.setCids("");
                            frendBean2.setZids("");


                            if (u == difnum - 1) {
                                frendBean2.setViewType(3);
                            } else {
                                frendBean2.setViewType(2);
                            }
                            frendBeanList.add(frendBean2);
                        } else {
                            diffnum++;
                            if (diffnum == friendList.size()) {
                                frendBeanList.remove(frendBeanList.size() - 1);
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            uid.clear();

        }
        listsize = frendBeanList.size();
        sendMess(3);

    }

    private void sendMess(int what) {
        Message message = new Message();
        message.what = what;
        handler.sendMessage(message);
    }


    /**
     * 下载好友信息
     */
    public void DownFrend() {
        if (NetUtil.getConnectState(NewEndTaskActivity.this) != NetUtil.NetWorkState.NONE) {
            StringRequest stringRequest = new StringRequest(Request.Method.POST, URLConstants.HOST+"/appFrends_findFrendsSay.do",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String result) {
                            if (!TextUtils.isEmpty(result)) {
                                try {
                                    Gson gson = new Gson();

                                    FriendBackBean friendBackBean = gson.fromJson(result, FriendBackBean.class);
                                    if (friendBackBean.status == 0) {

                                        friendBeanList = friendBackBean.list;
                                        App.getDBcApplication().clearFriendsListTable();
                                        if (friendBeanList != null) {

                                            for (FriendBean bean : friendBeanList) {
                                                App.getDBcApplication().insertFriendsList(bean);
                                            }

                                        }
                                        DownFrendCalender();

                                    } else {
                                        sendMess(004);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    sendMess(004);
                                }
                            }
                        }

                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.d("TAG", "error:" + volleyError.toString());
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<>();
                    map.put("uId", userID);// "52432"
                    map.put("updateTime", updatetime);//"2015-01-01 00:00:00"
                    return map;
                }
            };
            stringRequest.setTag("friend");
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
            App.queues.add(stringRequest);
        } else {
            Toast.makeText(NewEndTaskActivity.this, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
            pull_refresh_scrollview.onRefreshComplete();
        }
    }


    /**
     * 下载所有日程信息
     */
    public void DownFrendCalender() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLConstants.HOST+"/appFrends_downFrendsCalendar.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();

                                FriendDownBackBean findFrendsSayBean = gson.fromJson(result, FriendDownBackBean.class);
                                Log.e("TAG", result);
                                if (findFrendsSayBean.status == 0) {

                                    sharedPrefUtil
                                            .putString(
                                                    NewEndTaskActivity.this,
                                                    ShareFile.USERFILE,
                                                    ShareFile.PERSONDOWNTIME,
                                                    findFrendsSayBean.downTime);

                                    firendDownBeanList = findFrendsSayBean.list;
                                    friendDeleteScheduleBeanList = findFrendsSayBean.delList;

//                                    App.getDBcApplication().clearFriendDownAllScheduleBea();

                                    if (firendDownBeanList != null) {
                                        for (FriendDownAllScheduleBean bean : firendDownBeanList) {
                                            App.getDBcApplication().insertFriendSchedule(bean);
                                        }
                                        if (friendDeleteScheduleBeanList != null) {
                                            for (FriendDeleteScheduleBean bean : friendDeleteScheduleBeanList) {
                                                App.getDBcApplication().deleteFriendSchedule(bean.dataId);
                                            }
                                        }

                                    }
                                    DBtoAllList();
                                } else {
                                    sendMess(004);
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                                sendMess(004);
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userID);// "52432"
                map.put("updateTime", persondowntime);//"2015-01-01 00:00:00"
                Log.e("TAG", URLConstants.HOST+"/appFrends_downFrendsCalendar.do?uId=" + userID + "&updateTime=" + persondowntime);
                return map;
            }
        };
        stringRequest.setTag("allfriendcalender");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (lyb != null){
            unregisterReceiver(lyb);
        }
    }

    private boolean endtype = false;

    class lybo extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Integer.valueOf(intent.getExtras().get("l").toString()) == 1) {
                endtype = true;
                DownFrend();
            }
        }
    }
}
